package com.tedu.bill.demo7;

import java.util.Arrays;

/**
 * Author：毕龙
 * Date: 2024/4/16 19:26
 */
public class TestPolymorphism2 {
    public static void main(String[] args) {

       Pet[] pets = {
               new Dog("毕哥"),
               new Cat("平安"),
               new Cat("泽豪"),
               new Cat("王伟"),
               new Dog("程凯")
       };

        Pet[] pet = getPet(pets, 1);
        System.out.println(Arrays.toString(pet));
        Pet[] pet1 = getPet(pets, 2);
        System.out.println(Arrays.toString(pet1));
    }

    public static Pet[] getPet(Pet[] pets,int n){

        if(n == 1){
            int countDog = 0;
            //这是狗宠物
            //判断有多少只狗
            for (int i = 0; i < pets.length; i++) {
                //通过instanceof判断是否为狗
                if(pets[i] instanceof  Dog){
                    //狗的数量加1
                    countDog++;
                }
            }
            //创建狗的数组
            Dog[] dogs = new Dog[countDog];
            int indexDog = 0;
            for (int i = 0; i < pets.length; i++) {
                //通过instanceof判断是否为狗
                if(pets[i] instanceof  Dog){
                    //将狗放进狗的数组
                    dogs[indexDog++] = (Dog)pets[i];
                }
            }

            return dogs;
        }else{
            int countCat = 0;
            //这是狗宠物
            //判断有多少只狗
            for (int i = 0; i < pets.length; i++) {
                //通过instanceof判断是否为狗
                if(pets[i] instanceof  Cat){
                    //狗的数量加1
                    countCat++;
                }
            }
            //创建狗的数组
            Cat[] cats = new Cat[countCat];
            int indexCat = 0;
            for (int i = 0; i < pets.length; i++) {
                //通过instanceof判断是否为狗
                if(pets[i] instanceof  Cat){
                    //将狗放进狗的数组
                    cats[indexCat++] = (Cat)pets[i];
                }
            }

            return cats;
        }
    }

}
